package com.zzd.controller;

import com.zzd.entity.Music;
import com.zzd.entity.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RestController
public class Mp3Controller {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/listMusic")
    public Response<List<Music>> listAllMusic() {
        List<Music> music;
        music = jdbcTemplate.query("SELECT * FROM music", new RowMapper<Music>() {
            @Override
            public Music mapRow(ResultSet resultSet, int i) throws SQLException {
                return Mp3Controller.this.createMusic(resultSet);
            }
        });
        return new Response<>(music, "获取成功", 0);
    }
    @RequestMapping("/getMusic/{id}")
    public Response<Music> getMusic(@PathVariable("id") String id) {
        List<Music> musicList = jdbcTemplate.query("SELECT * FROM music WHERE id=?", new


                String[]{id}, new RowMapper<Music>() {
            @Override
            public Music mapRow(ResultSet resultSet, int i) throws SQLException {
                return Mp3Controller.this.createMusic(resultSet);
            }
        });
        if (musicList.size() > 0) {
            return new Response<>(musicList.get(0), "获取成功", 0);
        } else {
            return new Response<>(null, "获取失败：不存在该 ID 资源", 400);
        }
    }
    private Music createMusic(ResultSet resultSet) throws SQLException {
        int id = resultSet.getInt("id");
        String musicPath = resultSet.getString("url");
        String lyricPath = resultSet.getString("lyric_path");
        String ext = resultSet.getString("ext");
        String title = resultSet.getString("title");
        String author = resultSet.getString("author");
        Music music = new Music();
        music.setId(id);
        music.setTitle(title);
        music.setAuthor(author);
        music.setUrl(musicPath);
        music.setExt(ext);
        music.setLyricPath(lyricPath);
        return music;
    } }